package main

import (
	"fmt"
	"sort"
)

//#link: https://leetcode-cn.com/problems/top-k-frequent-words/
func main() {
	words := []string{"i", "love", "leetcode", "i", "love", "coding"}
	k := 3
	fmt.Println(topKFrequent(words, k))
}

func topKFrequent(words []string, k int) []string {
	tempMap := make(map[string]int)
	for _, word := range words {
		tempMap[word]++
	}

	result := make([]string, 0, len(tempMap))
	for pair := range tempMap {
		result = append(result, pair)
	}
	sort.Slice(result, func(i, j int) bool {
		s, t := result[i], result[j]
		return tempMap[s] > tempMap[t] || tempMap[s] == tempMap[t] && s < t
	})
	return result[:k]

}
